using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Serialization;
using Awaiter;
using Nsb.Classes;

namespace Yoshi.Classes
{
    [IgnoreNamespace]
    public class CommentData : SavableData
    {
        public const string FeedRx = "comment";

        private static readonly string PartitionKey = Uri.DbPath("comments");
        //public List<CommentItem> Comments;

        public void WriteCommentAw(Await awp, string itemId, string msg)
        {
            Debug.Assert(itemId != null, "WriteCommentAw itemId != null");
            CommentItem fd = new CommentItem(msg);
            string rowKey = itemId;

            new Await()
                .AddDl(delegate(Await aw) { AppendBlobStringAw(aw, PartitionKey, rowKey, FeedRx, Json.Stringify(fd)); })
                .Commit(awp);
        }

        public void GetCommentsAw(Await awp, string itemId)
        {
            string rowKey = itemId;
            new Await()
                .AddAw(RetrieveBlobStringAw, PartitionKey, rowKey)
                .HandleDl(Exceptions.BlobLoadError, Await.RethrowAw)
                .AddDx(delegate(Await aw)
                       {
                           string content = (string) aw[ResultRx];
                           content = CleanListData(content);
                           awp[ResultRx] = aw[ResultRx] != null ? Json.Parse("[" + content + "]") : null;
                           //Comments = (List<CommentItem>)awp[rxKey];
                       })
                .Commit(awp);
        }

        public static void NewGetAw(Await awp, string itemId)
        {
            CommentData dta = new CommentData();
            new Await()
                .AddAw(dta.GetCommentsAw, itemId)
                .HandleDl(Exceptions.BlobLoadError, Await.RethrowAw)
                .Commit(awp);
        }

        public static void DeleteCommentAw(Await awp, string id)
        {
            DeleteItemAw(awp, PartitionKey, id);
        }
    }
}